import { MockMethod } from 'vite-plugin-mock'
import { ServerType, ServerStatus, ServerUsageStatus, ServerEnvironment } from '../../src/model/server-model'
import { ApiResponse } from '../../src/model/common-model'
import { faker } from '@faker-js/faker'

// 模拟服务器数据
const servers = Array.from({ length: 30 }).map((_, index) => {
  const id = index + 1
  
  // 随机生成服务器类型
  const serverTypeOptions = [
    ServerType.WEB,
    ServerType.DATABASE,
    ServerType.APPLICATION,
    ServerType.FILE,
    ServerType.CACHE,
    ServerType.PROXY,
    ServerType.OTHER
  ]
  const serverType = serverTypeOptions[Math.floor(Math.random() * serverTypeOptions.length)]
  
  // 随机生成服务器状态
  const serverStatusOptions = [
    ServerStatus.ONLINE,
    ServerStatus.OFFLINE,
    ServerStatus.MAINTENANCE,
    ServerStatus.DECOMMISSIONED
  ]
  const serverStatus = serverStatusOptions[Math.floor(Math.random() * serverStatusOptions.length)]
  
  // 随机生成使用状态
  const usageStatusOptions = [
    ServerUsageStatus.IN_USE,
    ServerUsageStatus.AVAILABLE,
    ServerUsageStatus.RESERVED,
    ServerUsageStatus.RETIRED
  ]
  const usageStatus = usageStatusOptions[Math.floor(Math.random() * usageStatusOptions.length)]
  
  // 随机生成环境
  const environmentOptions = [
    ServerEnvironment.DEVELOPMENT,
    ServerEnvironment.TESTING,
    ServerEnvironment.PRODUCTION
  ]
  const environment = environmentOptions[Math.floor(Math.random() * environmentOptions.length)]
  
  // 模拟IP地址
  const ip = `${faker.number.int({min: 10, max: 192})}.${faker.number.int({min: 0, max: 255})}.${faker.number.int({min: 0, max: 255})}.${faker.number.int({min: 1, max: 254})}`
  
  // CPU型号列表
  const cpuModels = [
    'Intel Xeon E5-2680 v4',
    'Intel Xeon Gold 6240R',
    'AMD EPYC 7302P',
    'AMD EPYC 7542',
    'Intel Xeon Platinum 8380',
    'AMD EPYC 7763'
  ]
  
  // 操作系统版本列表
  const osList = [
    'CentOS Linux 7 (Core)',
    'Ubuntu 20.04 LTS',
    'Debian 11',
    'Red Hat Enterprise Linux 8',
    'Rocky Linux 8.5'
  ]
  
  // 随机生成CPU核心数和线程数
  const cpuCores = faker.helpers.arrayElement([8, 12, 16, 24, 32, 48, 64])
  const cpuThreads = cpuCores * (Math.random() > 0.5 ? 1 : 2)
  
  // 随机生成内存大小(GB)
  const memorySizes = [16, 32, 64, 128, 256, 512]
  const memorySize = faker.helpers.arrayElement(memorySizes)
  
  // 随机生成磁盘大小(GB)
  const diskSize = faker.helpers.arrayElement([240, 480, 960, 1024, 2048, 4096, 8192])
  
  // 创建磁盘信息JSON
  const createDiskInfo = () => {
    const disks = {}
    const diskNames = ['sda', 'sdb', 'sdc', 'sdd', 'nvme0n1', 'nvme1n1']
    const diskCount = Math.floor(Math.random() * 3) + 1 // 1-3个磁盘
    
    for (let i = 0; i < diskCount; i++) {
      const diskName = diskNames[i]
      const diskSizeGB = Math.floor(diskSize / diskCount)
      const mountPoint = i === 0 ? '/' : `/data${i}`
      
      disks[diskName] = {
        size_gb: diskSizeGB,
        mount: mountPoint
      }
    }
    
    return JSON.stringify(disks)
  }
  
  // 购买日期（1-3年内的随机日期）
  const purchaseDate = faker.date.past({ years: 3 }).toISOString()
  
  // 生成一个0到3000小时的运行时长
  const uptime = faker.number.float({ min: 1, max: 3000, fractionDigits: 1 })
  
  // 只给一部分服务器添加物理信息（这样可以测试有无物理信息的情况）
  const hasPhysicalInfo = id % 3 !== 0 // 2/3的服务器有物理信息
  
  return {
    id,
    ip,
    hostname: `server-${faker.word.sample()}-${id}`,
    product_line: faker.helpers.arrayElement(['电商', '支付', '物流', '社交', '游戏', '办公', '教育']),
    server_type: serverType,
    server_status: serverStatus,
    usage_status: usageStatus,
    environment: environment,
    sn: faker.string.alphanumeric(12).toUpperCase(),
    rack_location: `${faker.string.alpha(1).toUpperCase()}${faker.number.int({min: 1, max: 20})}-${faker.number.int({min: 1, max: 42})}`,
    // 物理信息字段
    ...(hasPhysicalInfo ? {
      cpu_model: faker.helpers.arrayElement(cpuModels),
      cpu_cores: cpuCores,
      cpu_threads: cpuThreads,
      memory_size: memorySize,
      disk_size: diskSize,
      disk_info: createDiskInfo(),
      system_version: faker.helpers.arrayElement(osList),
      kernel_version: `${faker.number.int({min: 3, max: 5})}.${faker.number.int({min: 10, max: 19})}.${faker.number.int({min: 0, max: 100})}-${faker.number.int({min: 1, max: 1000})}.el${faker.number.int({min: 7, max: 9})}.x86_64`,
      uptime: uptime,
      purchase_date: purchaseDate
    } : {}),
    created_at: faker.date.past().toISOString(),
    updated_at: faker.date.recent().toISOString(),
    notes: Math.random() > 0.3 ? faker.lorem.sentence() : ''
  }
})

export default [
  // 获取服务器列表
  {
    url: '/api/v1/servers/',
    method: 'get',
    response: (req: any) => {
      const { page = 1, page_size = 10, ip, hostname, product_line, server_type, server_status, usage_status, environment } = req.query
      
      let filteredServers = [...servers]
      
      // 处理筛选条件
      if (ip) {
        filteredServers = filteredServers.filter(s => s.ip.includes(ip))
      }
      
      if (hostname) {
        filteredServers = filteredServers.filter(s => s.hostname.toLowerCase().includes(hostname.toLowerCase()))
      }
      
      if (product_line) {
        filteredServers = filteredServers.filter(s => s.product_line === product_line)
      }
      
      if (server_type) {
        filteredServers = filteredServers.filter(s => s.server_type === server_type)
      }
      
      if (server_status) {
        filteredServers = filteredServers.filter(s => s.server_status === server_status)
      }
      
      if (usage_status) {
        filteredServers = filteredServers.filter(s => s.usage_status === usage_status)
      }
      
      if (environment) {
        filteredServers = filteredServers.filter(s => s.environment === environment)
      }
      
      // 处理分页
      const total = filteredServers.length
      const start = (Number(page) - 1) * Number(page_size)
      const end = start + Number(page_size)
      const serversList = filteredServers.slice(start, end)
      
      return {
        code: 0,
        errorMsg: '',
        data: serversList || [], // 确保始终返回数组
        total
      }
    }
  },
  
  // 获取服务器详情
  {
    url: '/api/v1/servers/:id',
    method: 'get',
    response: (req: any) => {
      const { id } = req.params
      const server = servers.find(s => s.id === Number(id))
      
      if (server) {
        return {
          code: 0,
          errorMsg: '',
          data: server
        }
      } else {
        return {
          code: 404,
          errorMsg: `服务器ID ${id} 不存在`,
          data: null
        }
      }
    }
  },
  
  // 创建服务器
  {
    url: '/api/v1/servers/',
    method: 'post',
    response: (req: any) => {
      const { body } = req
      const newId = servers.length + 1
      
      const newServer = {
        id: newId,
        ip: body.ip,
        hostname: body.hostname,
        product_line: body.product_line,
        server_type: body.server_type,
        server_status: body.server_status,
        usage_status: body.usage_status,
        environment: body.environment || ServerEnvironment.DEVELOPMENT,
        sn: body.sn || '',
        rack_location: body.rack_location || '',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        notes: body.notes || ''
      }
      
      servers.push(newServer)
      
      return {
        code: 0,
        errorMsg: '',
        data: newServer
      }
    }
  },
  
  // 更新服务器
  {
    url: '/api/v1/servers/:id',
    method: 'put',
    response: (req: any) => {
      const { id } = req.params
      const { body } = req
      
      const serverIndex = servers.findIndex(s => s.id === Number(id))
      
      if (serverIndex >= 0) {
        const updatedServer = {
          ...servers[serverIndex],
          ...body,
          updated_at: new Date().toISOString()
        }
        
        servers[serverIndex] = updatedServer
        
        return {
          code: 0,
          errorMsg: '',
          data: updatedServer
        }
      } else {
        return {
          code: 404,
          errorMsg: `服务器ID ${id} 不存在`,
          data: null
        }
      }
    }
  },
  
  // 删除服务器
  {
    url: '/api/v1/servers/:id',
    method: 'delete',
    response: (req: any) => {
      const { id } = req.params
      const serverIndex = servers.findIndex(s => s.id === Number(id))
      
      if (serverIndex >= 0) {
        servers.splice(serverIndex, 1)
        
        return {
          code: 0,
          errorMsg: '',
          data: {
            success: true
          }
        }
      } else {
        return {
          code: 404,
          errorMsg: `服务器ID ${id} 不存在`,
          data: null
        }
      }
    }
  }
]
